<!-- tinymc富文本 -->
<template>
  <div>
    <div class="article-container">
        <editor
            class="editors"
            v-model="myValue"
            :init="init"
            :disabled="disabled"
            @onClick="onClick"
            ref="tinymce"
        >
        </editor>
        <div class="search-image">
            <el-input placeholder="请输入内容" clearable v-model="searchImg" class="input-img-search">
                <el-button slot="append" icon="el-icon-search" @click="getImageList" :loading="ImgListLoading"></el-button>
            </el-input>
            <div class="image-box">
                <div class="i-list" v-for="(item,index) in imgList" :key="index">
                    <img :src="item.url" :alt="item.title" :title="item.title" class="img-content">
                    <div class="img-name" v-html="ellipsisFn(item.title)"></div>
                </div>
            </div>
        </div>
    </div>
    <div>
         <Cropper :imgSrc="imgSrc" @closeCropper="closeCropper" @finishCropper="finishCropper"></Cropper>
    </div>
  </div>
</template>

<script>
import Cropper from "./cropper.vue";
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/skins/ui/oxide/skin.css";
import "@/assets/tinymce/zh_CN.js"; // 本地汉化
import "tinymce/themes/silver/theme";
import "tinymce/plugins/image";
import 'tinymce/plugins/media'
import 'tinymce/plugins/table'
import "tinymce/plugins/lists";
import "tinymce/plugins/contextmenu";
import "tinymce/plugins/wordcount";
import "tinymce/plugins/colorpicker";
import "tinymce/plugins/textcolor";
import 'tinymce/plugins/imagetools' // 图片裁剪插件
import "tinymce/icons/default"; // 图标 -解决测试环境找不icon问题
import { upload_image, search_image } from "@/api/aiChange";
export default {
  name: "tinymce",
  components: {
    Editor,
    Cropper
  },
  props: {
    //传入一个value，使组件支持v-model绑定
    value: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    plugins: {
      type: [String, Array],
      default:
        // ' anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools insertdatetime link lists   noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
        "lists image media table  wordcount imagetools",
    },
    toolbar: {
      type: [String, Array],
      default:
        // 'undo redo | searchreplace | bold  italic | underline | strikethrough | alignleft  aligncenter alignright | outdent indent  blockquote  removeformat subscript superscript code codesample hr bullist numlist link image charmap preview anchor pagebreak insertdatetime  table  forecolor backcolor'
        "undo redo |  formatselect | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists image media table | removeformat hr | testButton",
    },
    aiTitle: {
        type: String,
        default: "",
    }
  },
  data() {
      return {
      imgSrc: '', // 获取点击图片的地址
      imgClass: '', // 获取点击图片的类class
      //初始化配置
      init: {
        language_url: "@/asset/tinymce/langs/zh_CN.js", // 这里需要单独处理
        language: "zh_CN",
        height: '556px',
        width:'70%',
        plugins: this.plugins,
        toolbar: this.toolbar,
        branding: true,
        menubar: true,
        //此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
        //如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
        // images_upload_handler: (blobInfo, success, failure) => {
        //   const img = "data:image/jpeg;base64," + blobInfo.base64();
        //   success(img);
            // },
        images_upload_handler: function (blobInfo, succFun, failFun) {
          var formData;
          var file = blobInfo.blob();//转化为易于理解的file对象
        //   succFun(''data:image/jpeg;base64,' +blobInfo.base64()');
            formData = new FormData();
            formData.append('file', file, file.name );//此处与源文档不一样
            upload_image(formData).then(res => {
                // this.$message.success(res.message)
                let path = res.data.path
                succFun(path)
            }).catch((error) => {
                console.log('error', error)
            })
        },
        resize: true,
        // 图片点击事件
        setup: (editor) => {
            editor.on('click', (e) => {
                const targetNode = e.target;
                if (targetNode.nodeName === 'IMG') {
                    // 在这里处理你的图片点击逻辑
                    // this.imgSrc = targetNode.getAttribute('src');
                    // this.imgClass = targetNode.getAttribute('class');
                    // console.log('图片地址:', this.imgSrc);
                    //   const images = editor.dom.select('img');
                    //   editor.dom.setAttrib(images, 'src', 'http://apigame.metvv.com/public/storage/topic/20240626/90f5645cd71536ebdbc1b5635ebf2009.jpg');
                }
            });
            // 点击图片右键触发
            editor.on('contextmenu', (e) => {
                // 只有当右键点击的是图片时才执行
                if (e.target.nodeName === 'IMG') {
                    // 自定义内容，例如显示一个弹窗
                    // alert('图片右键菜单：自定义内容');
                }
            });
            editor.on('SetContent', () => {
                // 当内容设置时触发，例如通过API设置内容或用户操作
                const images = editor.dom.select('img');
                images.forEach((image,index) => {
                // 这里可以添加你的图片处理逻辑
                // 例如：修改图片的src属性或添加class
                editor.dom.setAttrib(image, 'class', `my-custom-class${index + 1}`);
                });
            })
            // 自定义按钮
            // editor.ui.registry.addButton('testButton', {
            //     text: '日记日期',
            //     tooltip: '插入日记日期',
            //     onAction: () => editor.insertContent("123456")
            // })
            // 添加悬浮 上下文工具栏
            editor.ui.registry.addContextToolbar('editcontrol', {
                //浮层的触发条件
                predicate: function (node) {
                //   return node.className === 'control';
                    return node.nodeName.toLowerCase() === 'img';
                },
                items: 'changecontrol removecontrol', //显示的工具列表
                position: 'selection', //工具栏放置位置  selection node line
                // scope: 'node',
            });
            // 浮层注册裁剪和删除按钮
            editor.ui.registry.addButton('changecontrol', {
                icon: 'crop',
                tooltip: '图片裁剪',
                onAction: (e) => {
                    const targetNode = editor.selection.getNode()
                    if (targetNode.nodeName === 'IMG') {
                        this.imgSrc = targetNode.getAttribute('src');
                        this.imgClass = targetNode.getAttribute('class');
                    }
                },
            });
        }
      },
      myValue: this.value,
      searchImg: '', // 搜索图片
      imgList: [], // 图片列表
      ImgListLoading: false
    };
  },
  mounted() {
      tinymce.init({
    });
  },
  methods: {
    //添加相关的事件，可用的事件参照文档=> https://github.com/tinymce/tinymce-vue => All available events
    //需要什么事件可以自己增加
    onClick(e) {
      this.$emit("onClick", e, tinymce);
    },
    clear() {
      this.myValue = "";
    },
    // 裁剪图片返回事件
    finishCropper(val) {
        // 插入图片到编辑器
        // this.$refs.tinymce.editor.selection.setContent(`<img src="${val.data}" alt="Image" />`);
        console.log('--------1111111--------------', val, this.myValue, this.$refs.tinymce.editor)
        this.Cropper_image_handler(val.file, (data) => {
            this.$refs.tinymce.editor.execCommand('mceInsertContent', false, `<img src="${data}" />`);
        }, (error) => {

        })
        // 获取最新内容
        // const latestContent = this.$refs.tinymce.editor.selection.getContent();
        // console.log(latestContent); // 这里应该能获取到最新的内容
    },
    // 裁剪图片上传
    Cropper_image_handler(file, succFun, failFun) {
        var formData, file;
        formData = new FormData();
        formData.append('file', file, file.name );//此处与源文档不一样
        upload_image(formData).then(res => {
            this.$message.success(res.message)
            console.log(res)
            succFun(res.data.path)
        }).catch(() => {

        })
    },
    // 裁剪图片取消
    closeCropper() {
        this.imgSrc = ''
        this.imgClass = ''
    },
    // 超出部分隐藏且以省略号形式出现
    ellipsisFn(name) {
    //   /<[^>]+>/g.test(name)
       return name.length >  13 ? name.substr(0,13) + "..." : name
    },
    // 搜索图片获取列表
    getImageList: function () {
        this.ImgListLoading = true
        let obj = {
            form: {
                title: this.searchImg
            }
        }
        search_image(obj).then(res => {
           console.log(res)
           this.imgList = res.data.data
           this.ImgListLoading = false
        }).catch(err => {
           this.ImgListLoading = false
        })
    }
  },
  watch: {
    value(newValue) {
       this.myValue = newValue;
    },
    myValue(newValue) {
      this.$emit("input", newValue);
    },
    aiTitle: {
        handler(newValue,oldValue) {
            console.log('newValue', newValue, this.aiTitle)
            console.log('oldValue', oldValue)
            if(newValue) {
                this.searchImg = newValue
                this.getImageList()
            }
        },
        immediate:true
    },
  },
};
</script>
<style scoped lang="scss">
.article-container{
    display: flex;
    justify-content: space-between;
    .search-image{
        flex: 1;
        margin-left:20px;
    }
    .input-img-search{
       margin-bottom: 20px;
       :deep(.el-input-group__append) {
          background-color: #1890ff;
          color: #fff;
          border-color: #1890ff;
       }
    }
    .image-box{
        display: grid;
        grid-template-columns: 200px 200px;
        grid-gap: 30px;
        flex-wrap: wrap;
        height: 520PX;
        overflow: auto;
        .i-list{
           width: 200px;
           height:160px;
           margin-bottom: 20px;
        }
        .img-content{
           width: 100%;
           height: 100%;
           object-fit: cover;
           border-radius: 12px;
        }
        .img-name{
            line-height: 25px;
        }
    }
}
</style>
